package com.hanxiaozhang.filter;

import com.alibaba.fastjson.JSON;
import com.hanxiaozhang.constant.Constant;
import com.hanxiaozhang.filter.body.BodyReaderHttpServletRequestWrapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.http.HttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


/**
 * 功能描述: <br>
 * 〈请求参数日志过滤器〉
 *
 * @Author:hanxiaozhang
 * @Date: 2020/7/20
 */
@Slf4j
@Component
public class RequestLogFilter extends ZuulFilter {


    /**
     * 返回过滤器的类型
     * 类型：pre、route、post、error等
     *
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 返回一个int值来指定同一类型过滤器的执行顺序，不同的过滤器允许返回相同的数字
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return -1;
    }

    /**
     * 返回一个boolean值来判断该过滤器是否需要执行
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器的具体逻辑
     *
     * @return
     */
    @Override
    public Object run() {

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest serverHttpRequest = currentContext.getRequest();
        String method = serverHttpRequest.getMethod();
        // 处理跨域Post发送两次请求，打印两遍日志问题
        if (Constant.OPTIONS.equals(method)) {
            return null;
        }
        log.info("-------------------REQUEST-START-----------------");
        String contentType = serverHttpRequest.getHeader(Constant.CONTENT_TYPE);
        // 记录下请求内容
        log.info("URL: [{}]", serverHttpRequest.getRequestURL().toString());
        log.info("HTTP-METHOD: [{}]", method);
        log.info("Content-Type: [{}]", contentType);
        log.info("AUTHORIZATION: [{}]", serverHttpRequest.getHeader(Constant.CONTEXT_TOKEN));
        log.info("USER_AGENT: [{}]", serverHttpRequest.getHeader(Constant.USER_AGENT));
        if (contentType != null && contentType.contains(Constant.APP_JSON)) {
            //记录application/json时的传参
            HttpServletRequestWrapper httpServletRequestWrapper = (HttpServletRequestWrapper) serverHttpRequest;
            BodyReaderHttpServletRequestWrapper wrapper = (BodyReaderHttpServletRequestWrapper)
                    httpServletRequestWrapper.getRequest();
            log.info("Request Parameters: \n [{}]", wrapper.getBody());
        } else {
            //记录请求的键值对
            log.info("Request Parameters: \n [{}]", FilterUtil.handleInputParameters(serverHttpRequest.getParameterMap()));
        }
        return null;

    }


}
